# 安装基础环境
sudo apt-get install -y ca-certificates curl software-properties-common apt-transport-https curl
curl -s https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo apt-key add -
# 执行配置k8s阿里云源  
echo "deb https://mirrors.aliyun.com/kubernetes/apt/ kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list
# 执行更新
sudo apt-get update -y
# 安装kubeadm、kubectl、kubelet  
sudo apt-get install -y kubelet=1.23.1-00 kubeadm=1.23.1-00 kubectl=1.23.1-00
# 阻止自动更新(apt upgrade时忽略)。所以更新的时候先unhold，更新完再hold。
sudo apt-mark hold kubelet kubeadm kubectl

# 修改kubeadm-config.yaml 配置文件IP
IP=`hostname -I | awk '{print$1}'`
echo $IP
sed -i "s#advertiseAddress: [^,]*#advertiseAddress: $IP#g" kubeadm-config.yaml

# 从国内镜像拉取
sudo docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-apiserver:v1.23.10
sudo docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-controller-manager:v1.23.10
sudo docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-scheduler:v1.23.10
sudo docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-proxy:v1.23.10
sudo docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.6
sudo docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/etcd:3.5.1-0
sudo docker pull coredns/coredns:1.8.6
# 将拉取下来的images重命名为kubeadm config所需的镜像名字
sudo docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-apiserver:v1.23.10 k8s.gcr.io/kube-apiserver:v1.23.10
sudo docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-controller-manager:v1.23.10 k8s.gcr.io/kube-controller-manager:v1.23.10
sudo docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-scheduler:v1.23.10 k8s.gcr.io/kube-scheduler:v1.23.10
sudo docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-proxy:v1.23.10 k8s.gcr.io/kube-proxy:v1.23.10
sudo docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.6 k8s.gcr.io/pause:3.6
sudo docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/etcd:3.5.1-0 k8s.gcr.io/etcd:3.5.1-0
sudo docker tag coredns/coredns:1.8.6 k8s.gcr.io/coredns/coredns:v1.8.6


# 关闭swap
sudo swapoff -a
# 关闭防火墙
sudo ufw disable

# 删除相关进程
process=$(ps -aux | grep kube | grep -v grep | awk '{print $2}')
for id in $process
do
    sudo kill $id
done
# 删除相关配置文件和证书
sudo rm -rf /var/lib/etcd $HOME/.kube
sudo rm -rf /etc/kubernetes/*

# 删除相关容器
sudo docker stop $(sudo docker ps -a | grep kube | awk '{print $1}')
sudo docker rm $(sudo docker ps -aq --filter status="exited")
# 初始化
sudo kubeadm init --config kubeadm-config.yaml
# 配置用户
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

# 获取其他节点加入集群的命令
kubeadm token create --print-join-command

# 其他节点加入集群后，安装Calico
kubectl apply -f https://docs.projectcalico.org/v3.21/manifests/calico.yaml